package ru.acme.lab15.service;

import ru.acme.lab15.domain.client.Client;
import ru.acme.lab15.domain.email.Email;

public class EmailService {
	private final MyBlockingQueue<Email> queue = new MyBlockingQueue<Email>();
	private boolean closed = false;
	private Thread sendingThread;
	
	public EmailService() {
		sendingThread = new Thread(new Runnable() {

/*			public void run() {
				while (true) {
					if (sendingThread.isInterrupted()) {
						return;						
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						return;
					}
					while (true) {
						Email email = queue.tryTake();
						if (email == null) {
							break;
						}
						email.send();
					}
				}
			}
*/

			public void run() {
				synchronized(queue) {
					while (true) {
						Email email = queue.tryTake();
						if (email != null) {
							email.send();
							continue;
						}
						try {
							queue.wait();
						} catch (InterruptedException e) {
							return;
						}
					}
				}
			}
			
		});
		sendingThread.start();
	}

	public boolean sendEmail(Client client, String emailAddress) {
		if (closed) {
			return false;
		}
		queue.put(new Email(client, emailAddress));
		synchronized(queue) {
			queue.notify();
		}
		return true;
	}
	
	public void close() {
		closed = true;
		queue.waitUntilEmpty();
		sendingThread.interrupt();
	}
}
